package com.lkm.app_ui.ui;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.lkm.app.event.OnNetworkStateEvent;
import com.lkm.app_ui.AppConfig;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.ConfigReceiver;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.event.OnApkDownEvent;
import com.lkm.app_ui.help.OnSteelyardKeyEventHelp;
import com.lkm.app_ui.help.RootCommand;
import com.lkm.app_ui.help.WifiUtils;
import com.lkm.app_ui.m.fun.OnNfcDataEvent;
import com.lkm.app_ui.m.input.OnInputContentEvent;
import com.lkm.comlib.ui.BaseFragmentWrapActivity;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.market2_0.m.steelyardstatus.StatusInfo;
import com.lkm.market2_0.m.steelyardstatus.SteelyardStatusManagerModule;
import com.rockchip.rkapi.RKapi;
import com.lkm.app_ui.help.BeepManager;

import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseFragmentWrapActivity {

    @Override
    protected Fragment createFragment(Bundle savedInstanceState) {
        return new DelegateInitFragment();
    }

    private Handler mainHandler;


    // 语音来自:https://peiyin.wozhiyi.com/newproduction.html?tg=5362 标准-知洁 音量10 语速7 音调5
    BeepManager paySuccessBeepManager;
    BeepManager pleaseCardBeepManager;
    BeepManager pleaseScanQrBeepManager;

    private void initBeep() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<PlayBeepEvent>() {
            @Override
            public void onReceiver(PlayBeepEvent data) {
                if (data.getType() == PlayBeepEvent.TYPE_paySuccess)
                    if (paySuccessBeepManager != null) {

                        paySuccessBeepManager.playBeepSoundAndVibrate();
                    }
                if (data.getType() == PlayBeepEvent.TYPE_pleaseCard)
                    if (pleaseCardBeepManager != null) {

                        pleaseCardBeepManager.playBeepSoundAndVibrate();
                    }
                if (data.getType() == PlayBeepEvent.TYPE_pleaseScanQr)
                    if (pleaseScanQrBeepManager != null) {

                        pleaseScanQrBeepManager.playBeepSoundAndVibrate();
                    }


            }

            @Override
            public Class<PlayBeepEvent> getBusEventClass() {
                return PlayBeepEvent.class;
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
        new Thread() {
            @Override
            public void run() {
                super.run();

//                int[] rawNubs=new int[]{R.raw._0,R.raw._1,R.raw._2,R.raw._3,R.raw._4,R.raw._5,R.raw._6,R.raw._7,R.raw._8,R.raw._9};


//                numbersBeepManager[10]=new BeepManager(mView.getActivity(), R.raw.dot);


//                numbersBeepManager[11]=new BeepManager(mView.getActivity(), R.raw.delete);


//                numbersBeepManager[12]=new BeepManager(mView.getActivity(), R.raw.input);


//                welcomeBeepManager = new BeepManager(mView.getActivity(), R.raw.welcome);


//                pleasePayBeepManager = new BeepManager(mView.getActivity(), R.raw.please_pay_order);


                pleaseCardBeepManager = new BeepManager(getActivity(), R.raw.please_card);
                pleaseCardBeepManager.updatePrefs();

                pleaseScanQrBeepManager = new BeepManager(getActivity(), R.raw.please_scanqr);
                pleaseScanQrBeepManager.updatePrefs();

                paySuccessBeepManager = new BeepManager(getActivity(), R.raw.pay_success);
                paySuccessBeepManager.updatePrefs();


            }
        }.start();

        //RootCommand.runT("/system/bin/pm uninstall mark.satrace.cn");
    }

    private void destoryBeep() {


        if (pleaseCardBeepManager != null)
            pleaseCardBeepManager.close();
        pleaseCardBeepManager = null;

        if (pleaseScanQrBeepManager != null)
            pleaseScanQrBeepManager.close();
        pleaseScanQrBeepManager = null;

        if (paySuccessBeepManager != null)
            paySuccessBeepManager.close();
        paySuccessBeepManager = null;
    }


    private Activity getActivity() {
        return this;
    }

    @Override
    protected int configeContentLayoutID() {
        return R.layout.activity_main;
    }

    public void onClickShowB(View v) {
        if (RunTimeData.isXIANGCHENG) {
            RKapi.hideNavBar(false);
        }
        WifiUtils.getInstance().wifiManager.reconnect();
    }

    private TextView tv_tips_net, tv_tips_down;
    private TextView tv_tips_v, tv_tips_n;
    private TextView tv_tips_steelyard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        RootCommand.runT("echo \"PowerManagerService.noSuspend\" > /sys/power/wake_lock");


        if (!RunTimeData.isXIANGCHENG) {
//            RKapi.silentInstallApk(" /sdcard/xx111.apk","com.lkm.check_system",true);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            RKapi.hideNavBar(!false);
        }

        super.onCreate(savedInstanceState);
        mainHandler = new Handler(Looper.getMainLooper());

        tv_tips_net = (TextView) findViewById(R.id.tv_tips_net);
        tv_tips_net.setAlpha(0.5f);
        tv_tips_down = (TextView) findViewById(R.id.tv_tips_down);
        tv_tips_v = (TextView) findViewById(R.id.tv_tips_v);
        tv_tips_n = (TextView) findViewById(R.id.tv_tips_n);
        tv_tips_steelyard = (TextView) findViewById(R.id.tv_tips_steelyard);

        loophideBottomUIMenu();

//        LinkBusCycleWrapper.register(onDeviceStateEventObserver, holdCycleHelp(), CycleHelp.CycleType.Destroy);

        loopState();

        initBeep();


//        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {


//                OnSteelyardKeyEvent.sendKey(OnSteelyardKeyEvent.KEYCODE_FUN,new Handler(Looper.getMainLooper()));


        LinkBusCycleWrapper.register(new ObserverAutoNext<OnNetworkStateEvent>() {
            @Override
            public void onReceiver(OnNetworkStateEvent data) {


                String tips = data.extIsNetworkOK ? "" : "n";


                if (data.extNetType != ConnectivityManager.TYPE_WIFI) {
                    tv_tips_n.setText("4G");
                } else {
                    tv_tips_n.setText("wifi");
                }

                if (StringHelp.isEmpty(tips)) {
                    tv_tips_net.setVisibility(View.GONE);
                } else {

                    tv_tips_net.setVisibility(View.VISIBLE);
                    tv_tips_net.setText(tips);
                }

            }

            @Override
            public Class<OnNetworkStateEvent> getBusEventClass() {
                return OnNetworkStateEvent.class;
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);


        LinkBusCycleWrapper.register(new ObserverAutoNext<OnApkDownEvent>() {
            @Override
            public void onReceiver(OnApkDownEvent data) {

                String tips = "";
                if (data.status < 0) {
                    tips = "" + (data.status * -1);
                } else if (data.status == OnApkDownEvent.status_start) {
                    tips = "down";
                } else if (data.status == OnApkDownEvent.status_success) {
                    tips = "ok";
                } else if (data.status == OnApkDownEvent.status_fail) {
                    tips = "fail";
                }


                if (StringHelp.isEmpty(tips)) {
                    tv_tips_down.setVisibility(View.GONE);
                } else {

                    tv_tips_down.setVisibility(View.VISIBLE);
                    tv_tips_down.setText(tips);
                }

            }

            @Override
            public Class<OnApkDownEvent> getBusEventClass() {
                return OnApkDownEvent.class;
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);


//        LinkBusCycleWrapper.register(new ObserverAutoNext<CMDInitValueHandle.OnTipsEvent>(){


//                            tv_tips_net.setVisibility(View.GONE);

//                            tv_tips_net.setVisibility(View.VISIBLE);


//                return CMDInitValueHandle.OnTipsEvent.class;

//        },holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    private static String cardNoTemp = "";

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        boolean is = dispatchKeyEvent_(event);
        if (!is) return super.dispatchKeyEvent(event);
        return is;
    }

    public static boolean dispatchKeyEvent_(KeyEvent event) {
        if (ConfigReceiver.isremote_key) return false;


        if ((event.getKeyCode() >= KeyEvent.KEYCODE_A && event.getKeyCode() <= KeyEvent.KEYCODE_Z) || (event.getKeyCode() >= KeyEvent.KEYCODE_0 && event.getKeyCode() <= KeyEvent.KEYCODE_9)) {
            if (event.getAction() == KeyEvent.ACTION_DOWN)
                cardNoTemp += event.getNumber();
            return true;
        } else {
            return false;
        }
    }

    private void loophideBottomUIMenu() {
        hideBottomUIMenu(this.getWindow());
        mainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                loophideBottomUIMenu();
            }
        }, 2000);
    }


    public static void hideBottomUIMenu(Window window) {
        if (RunTimeData.isXIANGCHENG) {

            return;
        }


        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View v = window.getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            View decorView = window.getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    @Override
    protected void onDestroy() {
        mainHandler.removeCallbacksAndMessages(null);
        destoryBeep();
        super.onDestroy();
    }


    private void loopState() {

        mainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                SteelyardStatusManagerModule steelyardStatusManagerModule = (SteelyardStatusManagerModule) AppConst.getModuleManager().peekModule(SteelyardStatusManagerModule.class);

                if (steelyardStatusManagerModule != null) {
                    StatusInfo statusInfo = null;
                    try {
                        statusInfo = steelyardStatusManagerModule.getStatusInfoBySteelyardMac(RunTimeData.steelyardInfo.getSteelyardMac());
                    } catch (Exception e) {
                    }
                    MainActivity mView = MainActivity.this;
                    if (statusInfo == null) {
                        mView.showSteelyardConnectingTips(0);
                    } else if (statusInfo.isDisConnect()) {
                        mView.showSteelyardDisConnectTips(statusInfo.isException(), "");
                    } else if (statusInfo.isOnline()) {
                        mView.showSteelyardConnectEndips(true, "");
                    } else {
                        mView.showSteelyardConnectEndips(false, "掉线");
                    }

                    {
                        if (statusInfo != null)
                            if (statusInfo.getVoltage() <= 5.7) {
                                tv_tips_v.setVisibility(View.VISIBLE);
                                tv_tips_v.setText("请及时充电！" + statusInfo.getVoltage());
                            } else {
                                tv_tips_v.setVisibility(View.GONE);
                            }
                    }

                }
                loopState();
            }
        }, 1000);


    }


//                    mView.showSteelyardConnectingTips(data.getReConnectCount());

//                    mView.showSteelyardDisConnectTips(data.getIsError(), data.getErrorLog());

//                    mView.showSteelyardConnectEndips(true, data.getErrorLog());

//                    mView.showSteelyardConnectEndips(false, data.getErrorLog());


    public void showSteelyardDisConnectTips(boolean isError, String errorlog) {
        steelyardStateTips("台秤已经断开连接！！" + errorlog);
    }

    public void showSteelyardConnectingTips(int reConnectCount) {
        steelyardStateTips("台秤正在连接中：重连次数" + reConnectCount);
    }

    public void showSteelyardConnectEndips(boolean isSuccess, String errorlog) {
        if (isSuccess) {
            steelyardStateTips(null);
        } else {
            steelyardStateTips("台秤连接失败：" + errorlog);
        }
    }

    private void steelyardStateTips(String tips) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (StringHelp.isEmpty(tips)) {
                    tv_tips_steelyard.setVisibility(View.GONE);
                } else {

                    tv_tips_steelyard.setVisibility(View.VISIBLE);
                    tv_tips_steelyard.setText(tips);
                }
            }
        });

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        OnSteelyardKeyEventHelp.onSendKeyFormK(keyCode, mainHandler);

        return super.onKeyDown(keyCode, event);
    }
}
